import React, {useState} from "react";
import {Component} from "react";
import DPlayer from "react-dplayer";
import "./index.css"
import {AxioInstance} from "../../api/AxiosHelper";
import {GET_CHAPTER_DETAILES, GET_COURSE_CHAPTER_LIST} from "../../api/APIURLDefine";
import {Tree} from "antd";
import {CheckUserAuthorized} from "../../utils/Utils";
import {inject, observer} from "mobx-react";

@inject("globalStore", "userStore")
@observer
export default class VideoLesson extends Component<any, any> {
    constructor(props) {
        super(props);
        this.state = {
            chapter: {},
            details: {}
        }
    }

    componentDidMount() {
        //获取id信息
        const id = this.getId();
        AxioInstance.get(`${GET_CHAPTER_DETAILES}/${id}`).then((resp: any) => {
            console.log("章节详情", resp)
            this.setState({chapter: resp});
            if (resp.lessonDetails) {
                this.setState({details: resp.lessonDetails});
                AxioInstance.get(`${GET_COURSE_CHAPTER_LIST}/${resp.lessonDetails.courseId}`).then((data: any) => {
                    if (data) {
                        var ids = data.map((item) => item.id);
                        console.log(data)
                        this.setState({chapters: data, expand: ids});
                    }
                });
            }
        }).catch((error) => console.error(error));
    }

    getId() {
        var params = new URLSearchParams(this.props.history.location.search);
        var id = 1;
        if (params.has("id")) {
            id = parseInt(params.get("id"));
        }
        return id;
    }

    changeToLesson(data: any) {
        let path = "";
        const DOMAIN_NAME = this.props.globalStore.DOMainName;
        if (data.isLeaf) {
            //console.log("11111")
            switch (data.lessonType) {
                case 1:
                    path = "/article";
                    break;
                case 2:
                    path = "/video";
                    break;
                case 3:
                    path = "/vrExp";
                    break;
                case 4:
                    path = "/living";
                    break;
                default:
                    return;
            }
            if (!CheckUserAuthorized()) {
                this.props.globalStore.updateShowAuthModalVisible(true);
                return;
            }
            if (data.lessonType === 4) {
                return;
            }
            window.location.href = `/${DOMAIN_NAME}${path}?id=${data.id}`;
        }
    }

    private renderCourseDesign(chapters: Array<any>, keys: Array<any>) {
        const Demo: React.FC<{}> = () => {
            const [showLine, setShowLine] = useState(true);
            const [showIcon, setShowIcon] = useState(false);
            const [showLeafIcon, setShowLeafIcon] = useState(true);
            const [expand, updateExpand] = useState(keys);
            const onSelect = (selectedKeys, info) => {
                console.log("selected", selectedKeys, info);
            };

            return (
                <div>
                    {/* <div>
            <div className="course-title">
              <img src="./ui/CoursePage/icon_subject.png"></img>
              <span>课程设计</span>
            </div>
          </div> */}
                    <Tree
                        style={{width: "3.06rem", height: "3.41rem", textAlign: "left"}}
                        blockNode
                        showLine={showLine}
                        showIcon={showIcon}
                        selectable={false}
                        expandedKeys={expand}
                        onSelect={onSelect}
                        onExpand={(keys) => {
                            updateExpand(keys);
                        }}
                        defaultExpandAll={true}
                        titleRender={(data: any) => {
                            return (
                                <div className="tree-node-item">
                                    <div className="video-chapter-name" onClick={this.changeToLesson.bind(this, data)}>
                                        {(!data.isLeaf
                                            ? `第${data.index + 1}章 `
                                            : `第${data.index + 1}节 `) + data.title}
                                    </div>
                                </div>
                            );
                        }}
                        treeData={this.state.chapters !== undefined ? this.recursiveParseTree(null, chapters, expand) : null}
                    />
                </div>
            );
        };
        return (
            <div>
                <Demo></Demo>
            </div>
        );
    }

    render() {
        let result = null;
        if (this.state.chapters && this.state.expand) {
            result = this.recursiveParseTree(null, this.state.chapters, this.state.expand)
            console.log(result)
        }
        return (
            <div className="video-back">
                <div className="video-container">
                    <div className="video-page-header">
                        {/*<img src="./ui/icon_return_modal.png" className="video-back-btn"/>*/}
                        <div className="video-title">
                            {this.state.chapter.chapterName}
                        </div>
                    </div>
                    <div className="video-body">
                        <DPlayer
                            options={{
                                video: {
                                    url: this.state.details.lessonVideo,
                                    quality: [
                                        {
                                            name: '高清',
                                            url: this.state.details.lessonVideo,
                                            type: 'hls',
                                        },
                                        {
                                            name: '超清',
                                            url: this.state.details.lessonVideo,
                                            type: 'normal',
                                        },
                                    ],
                                    defaultQuality: 0,
                                },
                            }}
                        />
                    </div>
                </div>
                <div className="video-details">
                    <div className="video-header-right">
                        <div>
                            <img src="./ui/CoursePage/icon_subject.png" style={{
                                width: '0.39rem',
                                height: '0.39rem',
                                marginLeft: "0.11rem",
                                marginBottom: '0.05rem'
                            }}/>
                            <div>
                                考试测评
                            </div>
                        </div>
                        <div>
                            <img src="./ui/CoursePage/icon_subject.png" style={{
                                width: '0.39rem',
                                height: '0.39rem',
                                marginLeft: "0.11rem",
                                marginBottom: '0.05rem'
                            }}/>
                            <div>
                                考试测评
                            </div>
                        </div>
                        <div>
                            <img src="./ui/CoursePage/icon_subject.png" style={{
                                width: '0.39rem',
                                height: '0.39rem',
                                marginLeft: "0.11rem",
                                marginBottom: '0.05rem'
                            }}/>
                            <div>
                                考试测评
                            </div>
                        </div>
                        <div>
                            <img src="./ui/CoursePage/icon_subject.png" style={{
                                width: '0.39rem',
                                height: '0.39rem',
                                marginLeft: "0.11rem",
                                marginBottom: '0.05rem'
                            }}/>
                            <div>
                                考试测评
                            </div>
                        </div>
                    </div>
                    {
                        this.renderCourseDesign(this.state.chapters, this.state.expand)
                    }
                    <div className="video-hotRecommend">
                        <div className="video-hotRecommend-header">
                            热门推荐
                        </div>
                        <div className="video-hotRecommend-body">
                            <div>
                                <img src="./ui/CoursePage/icon_subject.png"
                                     style={{width: "2.2rem", height: "1.2rem"}}/>
                                <h3>羊乳粉工厂设计</h3>
                                <h4>主讲：西北大学食品科学与工程学院</h4>
                                <h4>时长：02：00：00</h4>
                            </div>
                            <div>
                                <img src="./ui/CoursePage/icon_subject.png"
                                     style={{width: "2.2rem", height: "1.2rem"}}/>
                                <h3>羊乳粉工厂设计</h3>
                                <h4>主讲：西北大学食品科学与工程学院</h4>
                                <h4>时长：02：00：00</h4>
                            </div>
                        </div>
                        <div className="video-hotRecommend-footer">
                            查看更多
                        </div>
                    </div>
                </div>
            </div>
        );
    }

    private drawNode(node: any) {
        console.log("节点", node)
        node?.map((element, index) => {
            return <dt>
                {
                    node.children?.length > 0 ?
                        node.children?.map((element, index) => {
                            return this.drawChild(element)
                        }) : null
                }

            </dt>

        })
        return null
    }

    private drawChild(node: any) {
        if (node.children?.length > 0) {
            this.drawChild(node.children)
        } else {
            console.log("子节点", node)
            return <dd>{node.title}</dd>

        }
    }

    private recursiveParseTree(
        parent: any,
        chapters: Array<any>,
        expand: Array<any>
    ) {
        var children = [];
        for (let index = 0; index < chapters.length; index++) {
            const element = chapters[index];
            if (!parent && !element.parent) {
                let child = {
                    title: element.chapterName,
                    id: element.id,
                    children: [],
                    icon: this.renderIcon(element.lessonType),
                    switcherIcon: null,
                    key: element.id,
                    isLeaf: children.length == 0,
                    index: children.length,
                    lessonType: element.lessonType,
                };
                child.children.push(
                    ...this.recursiveParseTree(element, chapters, expand)
                );
                child.isLeaf = child.children.length == 0;
                child.switcherIcon =
                    child.children.length > 0
                        ? this.renderIcon(
                        0,
                        expand.length == 0 || expand.indexOf(child.id) >= 0
                        )
                        : this.renderIcon(element.lessonType);
                children.push(child);
            } else if (parent && element.parent === parent.id) {
                let child = {
                    title: element.chapterName,
                    id: element.id,
                    children: [],
                    lessonType: element.lessonType,
                    icon: this.renderIcon(element.lessonType),
                    switcherIcon: null,
                    key: element.id,
                    isLeaf: children.length == 0,
                    index: children.length,
                };
                child.children.push(
                    ...this.recursiveParseTree(element, chapters, expand)
                );
                child.isLeaf = child.children.length == 0;
                child.switcherIcon =
                    child.children.length > 0
                        ? this.renderIcon(
                        0,
                        expand.length == 0 || expand.indexOf(child.id) >= 0
                        )
                        : this.renderIcon(element.lessonType);
                children.push(child);
            }
        }
        // console.log(children)
        return children;
    }

    private renderIcon(type, exp = false) {
        switch (type) {
            case 1:
                return (
                    <img
                        className="course-icon"
                        src="./ui/CoursePage/icon_article.png"
                    ></img>
                );
            case 2:
                return (
                    <img
                        className="course-icon"
                        src="./ui/CoursePage/icon_video.png"
                    ></img>
                );
            case 3:
                return (
                    <img className="course-icon" src="./ui/CoursePage/icon_VR.png"></img>
                );
            case 4:
                return (
                    <img
                        className="course-icon"
                        src="./ui/CoursePage/icon_live.png"
                    ></img>
                );
        }
        return (
            <img
                className="course-icon"
                src={
                    exp
                        ? "./ui/CoursePage/icon_minus_sign.png"
                        : "./ui/CoursePage/icon_add.png"
                }
            ></img>
        );
    }
}
